package cs.ubbcluj.ro.mps.states;

import java.io.IOException;
import java.io.PushbackInputStream;

import cs.ubbcluj.ro.mps.data.ConstrainImpl;
import cs.ubbcluj.ro.mps.data.ConstrainType;
import cs.ubbcluj.ro.mps.data.interfaces.Mps;
import cs.ubbcluj.ro.mps.reader.MpsInputStream;
import cs.ubbcluj.ro.mps.states.interfaces.State;
import cs.ubbcluj.ro.mps.states.utils.CharConstants;

/**
 * Represents the ROW section of the MPS file
 * 
 * @author avadas
 * @version 1.0
 */
public strictfp class ConstrainsState extends AbstractState {
    private boolean endOfSection = false;

    public ConstrainsState(final State nextState, final State errorState) {
	super(nextState, errorState);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public State nextState(final MpsInputStream input, final Mps mps)
	    throws IOException {

	if (consumeFirstColumn(input)) {
	    return this.errorState;
	}

	while (!this.endOfSection) {
	    final Character constrainType = (char) input.read();

	    if (consumeSpaces(input, 2)) {
		return this.errorState.nextState(input, null);
	    }

	    final StringBuffer nameBuffer = new StringBuffer();
	    int in = input.read();
	    while (in != CharConstants.LF && in != CharConstants.CR && in != 32) {
		nameBuffer.append((char) in);
		in = input.read();
	    }

	    if (in == 32) {
		this.consumeSpaces(input);
		in = input.read();
	    }

	    if (in == CharConstants.CR) {
		input.read();
	    }

	    final ConstrainImpl constrain = new ConstrainImpl(nameBuffer
		    .toString(), ConstrainType
		    .valueOf(constrainType.toString()));

	    mps.addConstrain(constrain);

	    if (consumeFirstColumn(input)) {
		return this.errorState;
	    }
	}
	return this.nextState;
    }

    /**
     * 
     * @param input
     *            the inputstream
     * @return true if was a parseError
     * @throws IOException
     *             see {@link IOException}
     */
    private boolean consumeFirstColumn(final PushbackInputStream input)
	    throws IOException {
	final int in = input.read();
	if (in != 32) {
	    if ((char) in == 'C') {
		this.endOfSection = true;
		input.unread(in);
		return false;
	    } else {
		return true;
	    }
	}
	return false;
    }
}
